﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace Xyzzer.AsyncUI
{
    public sealed partial class CustomDialog
    {
        public CustomDialog()
        {
            InitializeComponent();
        }

        private FrameworkElement RootFrameworkElement
        {
            get
            {
                return (FrameworkElement)Application.Current.RootVisual;
            }
        }

        /// <summary>
        /// Flag for preventing reentrancy in the Show() method.
        /// </summary>
        private bool shown;

        public async Task<string> Show(string title, string text, params string[] buttonTexts)
        {
            if (shown)
            {
                throw new InvalidOperationException();
            }

            shown = true;
            this.TitleTextBlock.Text = title;
            this.TextTextBlock.Text = text;

            var buttons = new List<ButtonBase>();

            foreach (var buttonText in buttonTexts)
            {
                var button = (ButtonBase)CloseButtonTemplate.LoadContent();
                button.Content = buttonText;
                buttons.Add(button);
                ButtonsPanel.Children.Add(button);
            }

            ResizeLayoutRoot();

            // Show dialog
            this.DialogPopup.IsOpen = true;
            this.SlideInAnimation.From =
                this.ContentBorderTranslation.X = RootFrameworkElement.ActualWidth;
            await this.SlideInStoryboard.BeginAsync();

            // Wait for button click
            var clickedButton = await buttons.WaitForClickAsync();

            // Hide dialog
            this.SlideOutAnimation.To = -RootFrameworkElement.ActualWidth;
            await this.SlideOutStoryboard.BeginAsync();
            this.DialogPopup.IsOpen = false;
            ButtonsPanel.Children.Clear();

            shown = false;
            return (string)clickedButton.Content;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            ResizeLayoutRoot();
            return base.ArrangeOverride(finalSize);
        }

        private void ResizeLayoutRoot()
        {
            var root = RootFrameworkElement;
            LayoutRoot.Width = root.ActualWidth;
            LayoutRoot.Height = root.ActualHeight;
        }
    }
}
